package com.qingyun.house.api.service;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.List;

import com.google.common.base.Strings;
import com.google.common.io.Files;
import com.qingyun.house.api.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;

@Service
public class FileService {


    @Value("${file.path}")
    private String filePath;

    public List<String> getImgPaths(List<MultipartFile> files) {
        if (Strings.isNullOrEmpty(filePath)) {
            filePath = getResourcePath();
        }
        List<String> paths = Lists.newArrayList();
        files.forEach(file -> {
            File localFile = null;
            try {
                if (!file.isEmpty()) {
                    localFile = saveToLocal(file, filePath); //FileUtil.
                    String path = StringUtils.substringAfterLast(localFile.getAbsolutePath(), filePath);
                    paths.add(path);
                }
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        });
        return paths;
    }

    public static String getResourcePath() {
        File file = new File(".");
        String absolutePath = file.getAbsolutePath();
        return absolutePath;
    }

    /**
     * 保存文件到本地
     * @param file
     * @param filePath
     * @return
     * @throws IOException
     */
    public  static  File saveToLocal(MultipartFile file, String filePath) throws IOException {  //@RequestParam
        File newfile = new File(filePath + "/" + Instant.now().getEpochSecond() + "/" + file.getOriginalFilename());
        if (!newfile.exists()) {
            newfile.getParentFile().mkdirs();
            newfile.createNewFile();
        }
        Files.write(file.getBytes(), newfile);
        return newfile;
    }
}
